package com.monitor.common.utils.page;

import com.monitor.common.constant.HttpStatus;
import com.monitor.common.core.page.PageDomain;
import com.monitor.common.core.page.TableDataInfo;
import com.monitor.common.core.page.TableSupport;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class PagingUtils {

    /**
     * 生成查询表单
     *
     * @param pageList 数据
     * @return 结果
     */
    public static TableDataInfo createPageInfoList(List<?> pageList) {
        if (CollectionUtils.isEmpty(pageList)) {
            return getDataTable(new ArrayList<>(), 0);
        }
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        return getDataTable(split(pageList, pageSize, pageNum), pageList.size());
    }

    /**
     * 生成查询表单
     *
     * @param list 数据
     * @param total 总件数
     * @return 结果
     */
    private static TableDataInfo getDataTable(List<?> list, long total) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(total);
        return rspData;
    }

    /**
     * @param list     需要分隔的集合
     * @param pageSize 指定分页size
     * @param pageNum  页号
     * @return 结果
     */
    public static List<?> split(List<?> list, int pageSize, int pageNum) {
        int limit = countStep(list.size(), pageSize);
        List<List<?>> splitList = Stream.iterate(0, n -> n + 1).limit(limit)
                .map(a -> list.stream().skip((long) a * pageSize).limit(pageSize).collect(Collectors.toList()))
                .collect(Collectors.toList());

        return splitList.get(pageNum - 1);
    }

    /**
     * 计算切分次数
     */
    private static Integer countStep(Integer size, int input) {

        return (size + input - 1) / input;
    }
}
